# from Iris import *
from Iris import Ui_MainWindow
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5.QtWidgets import *
import serial
import time
import threading


class Iris_Window(QMainWindow, Ui_MainWindow):
    def __init__(self,uart=None):
        super(Iris_Window, self).__init__()
        self.setupUi(self)
        self.uart_ready = True
        if uart is not None:
            self.uart = uart
        else:
            try:
                # self.uart = serial.Serial('/dev/ttyUSB0',115200)
                self.uart = serial.Serial('com5', 115200)
                self.text_view.append('uart connected')
            except:
                self.uart_ready = False
                self.text_view.append('uart failed')
        self.task_listening = threading.Thread(target=self.listen_uart, name='task listen')
        self.task_listening.start()

    def send_click(self):
        if self.uart_ready:
            self.uart.write(self.text_in.text().encode('ascii'))
            self.uart.write(b'\n')
        self.text_in.clear()
        pass

    def listen_uart(self):
        while True:
            if self.uart_ready:
                size = self.uart.inWaiting()
                if size > 0:
                    try:
                        msg = self.uart.read(size)
                        sb = str(msg, encoding="ascii")
                        pos = len(self.text_view.toPlainText()) + size

                        cursor = self.text_view.textCursor()  # 设置游标
                        cursor.movePosition(pos)
                        cursor.insertText(sb)
                        cursor.setPosition(pos)  # 游标位置设置为尾部
                        self.text_view.setTextCursor(cursor)  # 滚动到游标位置
                        self.uart.flushInput()  # 清空接收缓存区
                    except :
                        self.text_view.append('error')
                    time.sleep(0.01)

    def menu_bar_triger(self, action):
        action = action.text()
        if action == 'reset':
            pass
        elif action[:2] == 'ca':
            pass


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    my_pyqt_form = Iris_Window()
    my_pyqt_form.show()
    sys.exit(app.exec_())
